//
//  XCMVController.m
//  TTLestening
//
//  Created by dllo on 16/3/28.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "XCMVController.h"
#import "XCAVFlashPlayer.h"
#import "NetworkingHandlerOfBlock.h"
#import "XCModelForMVHeader.h"
#import <AVFoundation/AVFoundation.h>
#import "HYMVHeaderView.h"
#import "HYTableViewCellForMVMenu.h"
#import "HYModelForMVMenu.h"

#import "XCModelForEveryone.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

#define WIDGHT  self.view.frame.size.width
#define HEIGHT  self.view.frame.size.height

#define WIDGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667

@interface XCMVController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) XCModelForMVHeader *model;
@property (nonatomic, strong) XCAVFlashPlayer *avFlash;

@property (nonatomic, strong) HYMVHeaderView *viewForHeader;

@property (nonatomic, strong) NSMutableArray *arrayForDanmu;

@property (nonatomic, strong) NSMutableArray *arrForMVMenu;

@property (nonatomic, copy)NSString *picUrl;
@property (nonatomic, copy)NSString *url;
@end

@implementation XCMVController

//- (void)dealloc {
//
//    [self.avFlash.playItem removeObserver:self.avFlash forKeyPath:@"status"];
//    [self.avFlash.playItem removeObserver:self.avFlash forKeyPath:@"loadedTimeRanges"];
//       
//}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserverForName:@"postImageAndUrl" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            
            self.picUrl = [note.userInfo objectForKey:@"image"];
            
            NSLog(@"%@",self.url);
            
        }];
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self handleData];
    
    self.navigationController.navigationBarHidden = YES;
    
    [self handleDataForMVMenu];
    
    [self createTableView];
    
    self.avFlash = [XCAVFlashPlayer sharedFlashPlayerWithFrame:CGRectMake(0,0, WIDGHT, HEIGHT / 2.5)];
    [self.view addSubview:self.avFlash];

    self.view.backgroundColor = [UIColor whiteColor];
    
}

//- (void)viewWillDisappear:(BOOL)animated {
//    
//    [super viewWillDisappear:animated];
//
//    [[NSNotificationCenter defaultCenter] removeObserver:self.avFlash forKeyPath:@"status"];
//
//
//}

- (void)createBackButton {
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:button];
    button.frame = CGRectMake(10 * WIDGHTT, 20, 30 * WIDGHTT, 30 * HEIGHTT);
//    button.backgroundColor = [UIColor whiteColor];
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui-7"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)backAction:(UIButton *) button {

       [self.avFlash.playItem removeObserver:self.avFlash forKeyPath:@"status"];
    [self.avFlash.playItem removeObserver:self.avFlash forKeyPath:@"loadedTimeRanges"];

    [self.avFlash.play pause];
    [self.navigationController popToRootViewControllerAnimated:YES];

    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }


}

- (void)roteAction:(NSNotification *) noti {
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    // 向右横屏
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        
        [self setPlayerLayerFrame];
    }
    // 向左横屏
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        
        [self setPlayerLayerFrame];
        
    }if (orientation == UIInterfaceOrientationPortrait) {
        [self setPlayerLayerFramePortrait];
        
    }
    
    
}

- (void)setPlayerLayerFrame {
    
//    self.view.frame = CGRectMake(0, 0, WIDGHT, HEIGHT);
//    self.playerLayer.frame = CGRectMake(0, 0, WIDGHTA, HEIGHTA);
    
    self.tableView.alpha = 0;
}

- (void)setPlayerLayerFramePortrait {
    
//    self.frame = CGRectMake(0, 0, self.width, self.height);
//    self.playerLayer.frame = CGRectMake(0, 0, self.width, self.height);
    self.tableView.alpha = 1;
    
}


-(void)handleData {
    
    NSString *urlFront = @"http://api.dongting.com/song/video/";
    NSString *urlBack = @"?app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=9.2&active=1&net=2&openudid=71ae591d23e3955faffe1f13002174549b820ffe&idfa=766C509A-D4C4-4D11-89EA-A316DCF2B7CC&utdid=Vo%2FO9IPtv1UDAHSbJQCXwF%2F6&alf=201200&bundle_id=com.ttpod.music&latitude=38.88243&longtitude=121.5397";
    NSString *url = [urlFront stringByAppendingFormat:@"%@%@", self.value, urlBack];
    
  //http://api.danmaku.dongting.com/danmakus?limit=1500&mv_id=2260582&version=0

    NSString *urlForDanmu = @"http://api.danmaku.dongting.com/danmakus?limit=1500&mv_id=";
    NSString *urlForDanmuBack = @"&version=0";
    
    NSString *danmuUrl = [urlForDanmu stringByAppendingFormat:@"%@%@", self.value, urlForDanmuBack];
    
    [NetworkingHandler networkingNOSaveWithUrl:danmuUrl completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        self.arrayForDanmu = [NSMutableArray array];
        
        NSArray *array = [result objectForKey:@"danmaku"];
        NSArray* reversedArray = [[array reverseObjectEnumerator] allObjects];
        
        for (NSDictionary *dic in reversedArray) {
            
           // NSLog(@"%@", [dic objectForKey:@"m"]);
            
            [self.arrayForDanmu addObject:[dic objectForKey:@"m"]];
            
        }
        
        [self.avFlash passDamuArray:self.arrayForDanmu];
        
    }];
    
    
    
    [NetworkingHandler networkingNOSaveWithUrl:url completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        NSDictionary *dic = [result objectForKey:@"data"];
        self.model = [[XCModelForMVHeader alloc] init];
        [self.model setValuesForKeysWithDictionary:dic];
        self.url = [[self.model.mvList firstObject] objectForKey:@"url"];
        
        self.avFlash = [XCAVFlashPlayer sharedFlashPlayerWithFrame:CGRectMake(0, 0, WIDGHT, HEIGHT / 2.5)];
        
        [self.view addSubview:self.avFlash];
        [self createBackButton];
        [self.avFlash passUrl:[[self.model.mvList lastObject] objectForKey:@"url"]];
        
        [self.viewForHeader passModel:self.model];

    }];

    
    
}


- (void)createTableView {

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HEIGHT / 2.5 - 20, WIDGHT, HEIGHT - HEIGHT / 2.5  + 20) style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.viewForHeader = [[HYMVHeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDGHT, 100)];
    [self.viewForHeader.buttonForShare addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];

    self.tableView.tableHeaderView = self.viewForHeader;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HYTableViewCellForMVMenu" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"pool"];
    
}

#pragma mark 分享
- (void)shareAction:(UIButton *)button {
    
    //1、创建分享参数
    NSArray *imageArray = @[self.picUrl];
       
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:self.url
                                         images:imageArray
                                            url:[NSURL URLWithString:self.url]
                                          title:@"分享"
                                           type:SSDKContentTypeAuto];
        //2、分享（弹出分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"OK"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
    
    
}


- (void)handleDataForMVMenu {
    
    self.arrForMVMenu = [NSMutableArray array];
    
    NSString *strFor = @"http://api.dongting.com/sim/mv/2260582/similarity?app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPad4%2C4&f=f320&s=s330&imsi=&hid=&splus=9.2&active=1&net=2&openudid=2928af1fecbb94c32045ea1742d7f5be6defe28e&idfa=87EE45D3-F1BC-49C6-AD99-E17773876586&utdid=Vu9EaFGgHV4DAPqTc15UrKj8&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude=";
    
    [NetworkingHandler networkingNOSaveWithUrl:strFor completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        NSArray *arr = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in arr) {
            
            HYModelForMVMenu *model = [[HYModelForMVMenu alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.arrForMVMenu addObject:model];
        }
        
        [self.tableView reloadData];
        
    }];
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrForMVMenu.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 40;
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] init];
    

    label.frame = CGRectMake(0, 0, 100, 30);
    label.text = @"推荐MV";
    [view1 addSubview:label];
    
    return view1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 150;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HYModelForMVMenu *model = [self.arrForMVMenu objectAtIndex:indexPath.row];
    
    HYTableViewCellForMVMenu *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    
    [cell passModel:model];
    
    return cell;
}


















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
